package com.yang.config;

import org.apache.commons.collections.map.LinkedMap;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yds
 * @program spring-boot-shiro
 * @description 作为shiro框架配置类
 * @create 2020-10-22 11:13
 **/
@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager  securityManager){
        ShiroFilterFactoryBean shiroBean=new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroBean.setSecurityManager(securityManager);
        /*
           添加shiro的内置过滤器
           anno: 无需认证
           authc: 必须认证才能访问
           user: 必须拥有记住我功能才能使用的权限
           perms: 拥有对某个资源的权限
           role: 拥有某个角色
         */
        Map<String, String> filterMap= new LinkedMap();
        //授权正常，未授权则跳转到未授权页面  先授权后拦截
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/*","authc");


        shiroBean.setFilterChainDefinitionMap(filterMap);
        //设置请求拦截后跳转页面
        shiroBean.setLoginUrl("/toLogin");
        //设置未授权请求
        shiroBean.setUnauthorizedUrl("/unAuth");
        return shiroBean;
    }

    //SecurityManager
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("user") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    //创建realm对象,需要自定义
    @Bean(name="user")
    public UserRealm userRealm(){
        return  new UserRealm();
    }
}